﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entity;
using Web.Framework;
using Entity.Admin;
using Core;

namespace Service
{
    public class RoleService : BaseService<Role>
    {
        public RoleService(DBEntities db)
            : base(db)
        {

        }

        public override Role Create(Role entity)
        {
            if (db.Roles.Any(p => p.RoleName == entity.RoleName))
            {
                throw new ModelCheckException("RoleName", "名称不能重复");
            }
            if (string.IsNullOrEmpty(entity.ID))
            {
                entity.ID = Guid.NewGuid().ToString();
            }
            return base.Create(entity);
        }

        public override Role Save(Role entity)
        {
            if (db.Roles.Any(p => p.RoleName == entity.RoleName && p.ID != entity.ID))
            {
                throw new ModelCheckException("RoleName", "名称不能重复");
            }
            return base.Save(entity);
        }

        public Role CreateOrSave(Role entity)
        {
            if (db.Roles.AsNoTracking().Any(p => p.ID == entity.ID))
            {
                return Save(entity);
            }
            else
            {
                return Create(entity);
            }
        }

        public void SaveRoleUsers(Role role, IEnumerable<string> roleUserIds)
        {
            #region 先清除Users关系
            var dbtmp = new DBEntities();
            dbtmp.Roles.Find(role.ID).Users.Clear();
            dbtmp.SaveChanges();
            role.Users.Clear();
            #endregion

            var users = db.Users.Where(p => roleUserIds.Contains(p.ID));
            foreach (var item in users)
            {
                role.Users.Add(item);
            }
            Save(role);
        }

        public void SaveRoleMenus(Role role, IEnumerable<string> roleMenus)
        {
            #region 先清除Menus关系
            var dbtmp = new DBEntities();
            dbtmp.Roles.Find(role.ID).Menus.Clear();
            dbtmp.SaveChanges();
            role.Menus.Clear();
            #endregion

            var menus = db.Menus.Where(p => roleMenus.Contains(p.ID));
            foreach (var item in menus)
            {
                role.Menus.Add(item);
            }
            Save(role);
            //throw new NotImplementedException();
        }
    }
}
